//ObjectClone.java
package com.xyc.ch6;
class A implements Cloneable
{
	int i;
	public A(int ii)
	{
		i=ii;
	}
	public Object clone()
	{
		Object o=null;
		try
		{
			o=super.clone();
		}catch(CloneNotSupportedException e){
			System.out.println("A类对象不能克隆！");
		}
		return o;
	}
	public boolean equals(Object obj)
	{
		if(obj instanceof A)
			return ((A)obj).i==i;
		return false;
	}
	public String toString()
	{
		return ""+i;
	}
}

class B implements Cloneable
{
	A a;
	public B(int i)
	{
		a=new A(i);
	}
	//浅拷贝
	public Object clone()
	{
		Object o=null;
		try
		{
			o=super.clone();
		}catch(CloneNotSupportedException e){
			System.out.println("B类对象不能克隆！");
		}
		return o;
	}
}

class C implements Cloneable
{
	A a;
	public C(int i)
	{
		a=new A(i);
	}
	//深拷贝
	public Object clone()
	{
		C o=null;
		try
		{
			o=(C)super.clone();
		}catch(CloneNotSupportedException e){
			System.out.println("C类对象不能克隆！");
		}
		o.a=(A)o.a.clone();
		return o;
	}
}

class D{}

public class ObjectClone
{
	public static void main(String[] args) {
		A a1=new A(1);
		A a2=(A)a1.clone();
		System.out.println("a2是a1的克隆");
		if(a1==a2)
			System.out.println("a1、a2指向同一对象！");
		else
			System.out.println("a1、a2指向不同对象！");
		if(a1.equals(a2))
			System.out.println("a1、a2中的内容相等！");
		else
			System.out.println("a1、a2中的内容不相等！");

		B b1=new B(1);
		B b2=(B)b1.clone();
		System.out.println("b2是b1的克隆");
		if(b1==b2)
			System.out.println("b1、b2指向同一对象！");
		else
			System.out.println("b1、b2指向不同对象！");
		if(b1.a ==b2.a)
			System.out.println("b1.a、b2.a指向同一对象！");
		else
			System.out.println("b1.a、b2.a指向不同对象！");
		b2.a.i=10;
		System.out.println("b1.a.i="+b1.a.i);
		System.out.println("b2.a.i="+b2.a.i);

		C c1=new C(1);
		C c2=(C)c1.clone();
		System.out.println("c2是c1的克隆");
		if(c1==c2)
			System.out.println("c1、c2指向同一对象！");
		else
			System.out.println("c1、c2指向不同对象！");
		if(c1.a ==c2.a)
			System.out.println("c1.a、 c2.a指向同一对象！");
		else
			System.out.println("c1.a、 c2.a指向不同对象！");
		c1.a.i=10;
		System.out.println("c1.a.i="+c1.a.i);
		System.out.println("c2.a.i="+c2.a.i);

		D d=new D();
		if(d instanceof Cloneable)
			System.out.println("D类对象可以克隆！");
		else
			System.out.println("D类对象不能克隆！");
	}
}







